package com.maxima.attendance.actions;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;

import com.maxima.attendance.constants.Constants;
import com.maxima.attendance.daos.AdminDAO;
import com.maxima.attendance.interceptors.SessionValidator;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginLogoutAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private Map<String, Object> map = ActionContext.getContext().getSession();
	// for logging
	static Logger logger = Logger.getLogger(ProjectAction.class.getName());
	private AdminDAO adminDAO = new AdminDAO();

	@Override
	@Action(value = "refreshUsers", results = {
	@Result(name = "user", type = "tiles", location = "userHome.tiles"), @Result(name = "admin", type = "tiles", location = "adminUserStatus.tiles"), @Result(name = "error", location = "index.jsp")
	}, interceptorRefs = {
		@InterceptorRef(value = "defaultInterceptorStack")
	})
	public String execute() throws Exception {
		return SUCCESS;
	}

	@Action(value = "login", results = {
	@Result(name = "user", location = "showStatus.jsp"), @Result(name = "admin", type = "tiles", location = "adminHome.tiles"), @Result(name = "error", location = "index.jsp")
	})
	public String login() {
		this.password = ServletActionContext.getRequest().getParameter("password");
		String usertype = ServletActionContext.getRequest().getParameter("usertype");
		this.username = usertype.equals("admin") ? Constants.ADMINISTRATOR : ServletActionContext.getRequest().getParameter("username");
		if (!validateLogin()) {
			return ERROR;
		}
		return username.equals(Constants.ADMINISTRATOR) ? "admin" : "user";
	}

	@Action(value = "logout", results = {
		@Result(name = "success", location = "/index.jsp")
	}, interceptorRefs = {
		@InterceptorRef(value = "adminStack")
	})
	public String logout() {
		logger.info(map.get(Constants.ACTIVE_LOGIN) + " " + " Logout Successfully");
		SessionValidator.clearSession();
		return SUCCESS;
	}

	private boolean validateLogin() {
		if (adminDAO.checkLogin(username, password)) {
			if (username.equals(Constants.ADMINISTRATOR)) {
				map.put(Constants.ADMIN_LOGIN, true);
			} else {
				map.put(Constants.USER_LOGIN, true);
			}
			map.put(Constants.ACTIVE_LOGIN, username);
			logger.info(map.get(Constants.ACTIVE_LOGIN) + " " + " Login Successfully");
			return true;
		} else {
			return false;
		}
	}
}
